package dfbz.com.controller.student;

import dfbz.com.controller.BaseServlet;
import dfbz.com.model.Student;
import dfbz.com.pojo.Person;
import dfbz.com.service.StudentService;
import dfbz.com.service.impl.StudentServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@WebServlet("/student/*")
public class StudentServlet extends BaseServlet {

    private StudentService studentService = new StudentServiceImpl();


    public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //req.setCharacterEncoding("UTF-8");
        Map<String, String[]> map = req.getParameterMap();
        try {
            Person person = new Person();
            BeanUtils.populate(person, map);
            studentService.add(person);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //下一步 刷新页面(相当于再重新查询stuList，设置到Attribute)
        req.getSession().setAttribute("msg", "info");
        req.getSession().setAttribute("stuList", studentService.findAll());

        //req.getRequestDispatcher("/myView").forward(req, resp);
        resp.sendRedirect("index.jsp");
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //req.setCharacterEncoding("UTF-8");
        Map<String, String[]> map = req.getParameterMap();
        try {
            Person person = new Person();
            BeanUtils.populate(person, map);
            studentService.update(person);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //下一步 刷新页面(相当于再重新查询stuList，设置到Attribute)
        req.getSession().setAttribute("msg", "info");

        //req.getRequestDispatcher("/myView").forward(req, resp);
        resp.sendRedirect(req.getContextPath() + "/view/myView");
    }

    public void get(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String id = req.getParameter("id");
        Student stu = studentService.findById(id);
        if(null != stu){
            req.getSession().setAttribute("msg", "update");
            req.getSession().setAttribute("stu", stu);
            resp.sendRedirect(req.getContextPath() + "/view/myView");
        }
    }

    public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String id = req.getParameter("id");
        studentService.delById(id);
        //下一步 刷新页面(相当于再重新查询stuList，设置到Attribute)
        req.getSession().setAttribute("msg", "info");
        resp.sendRedirect(req.getContextPath() + "/view/myView");
    }


}
